package com.hxkj.controller.wechat.ueditor.upload;

import com.hxkj.controller.wechat.ueditor.PathFormat;
import com.hxkj.controller.wechat.ueditor.define.AppInfo;
import com.hxkj.controller.wechat.ueditor.define.BaseState;
import com.hxkj.controller.wechat.ueditor.define.FileType;
import com.hxkj.controller.wechat.ueditor.define.State;
import com.integral.mall.file.service.SysFileService;
import org.apache.tomcat.util.http.fileupload.FileItemIterator;
import org.apache.tomcat.util.http.fileupload.FileItemStream;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class BinaryUploader {

	public static final State save(HttpServletRequest request,
								   Map<String, Object> conf, SysFileService sysFileService) {
		FileItemStream fileStream = null;
		boolean isAjaxUpload = request.getHeader( "X_Requested_With" ) != null;

		if (!ServletFileUpload.isMultipartContent(request)) {
			return new BaseState(false, AppInfo.NOT_MULTIPART_CONTENT);
		}

		ServletFileUpload upload = new ServletFileUpload(
				new DiskFileItemFactory());

		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

		MultipartFile file = multipartRequest.getFile("upfile");

		String filename = file.getOriginalFilename();

		if ( isAjaxUpload ) {
            upload.setHeaderEncoding( "UTF-8" );
        }

		try {
			FileItemIterator iterator = upload.getItemIterator(request);

			if (filename == null) {
				return new BaseState(false, AppInfo.NOTFOUND_UPLOAD_DATA);
			}

			String savePath = (String) conf.get("savePath");
			String suffix = FileType.getSuffixByFilename(filename);

			filename = filename.substring(0,
					filename.length() - suffix.length());
			savePath = savePath + suffix;

			long maxSize = ((Long) conf.get("maxSize")).longValue();

			if (!validType(suffix, (String[]) conf.get("allowFiles"))) {
				return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE);
			}

			savePath = PathFormat.parse(savePath, filename);

            String saveNewPath = savePath.substring(1 , savePath.indexOf("."));
			String physicalPath = (String) conf.get("rootPath") ;

			StorageManager storageManager = new StorageManager();

            long size = file.getSize();

			if (size > maxSize) {
				return new BaseState(false, AppInfo.MAX_SIZE);
			}
            InputStream in = file.getInputStream();
			State storageState = storageManager.saveFileByInputStream(file.getInputStream(),
					physicalPath, maxSize,sysFileService,suffix.substring(1,suffix.length()),saveNewPath);

			if (storageState.isSuccess()) {
				storageState.putInfo("type", suffix);
				storageState.putInfo("original", filename + suffix);
			}

			return storageState;
		} catch (FileUploadException e) {
			return new BaseState(false, AppInfo.PARSE_REQUEST_ERROR);
		} catch (IOException e) {
		}
		return new BaseState(false, AppInfo.IO_ERROR);
	}

	private static boolean validType(String type, String[] allowTypes) {
		List<String> list = Arrays.asList(allowTypes);

		return list.contains(type);
	}
}
